<template>
  <div>
    <div class="detail_box">
      <el-row v-if="type==='list'" style="text-align: right;">
        <el-col>
          <el-button size="small" @click="submit(null, 'many')">提交审批</el-button>
          <!-- <el-button size="small" type="primary">导出交底单</el-button> -->
        </el-col>
      </el-row>
      <!-- <el-row v-else style="text-align: right;">
        <el-col>
          <el-button size="small">驳回</el-button>
          <el-button size="small" type="primary">通过审批</el-button>
        </el-col>
      </el-row> -->
      <el-row v-if="type==='list'">
        <el-col>
          <el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" v-loading="loading"
            @selection-change="handleSelectionChange">
            <el-table-column
              type="selection"
              :selectable="checkStatus"
              width="45">
            </el-table-column>
            <el-table-column prop="jobCode" label="交底单名称">
              <template slot-scope="scope">
                {{ jobTypes[scope.row.jobCode] }}
              </template>
            </el-table-column>
            <el-table-column prop="code" label="交底单编号">
            </el-table-column>
            <el-table-column prop="attachment" label="上传状态">
              <template slot-scope="scope">
                {{ scope.row.attachment ? '已上传' : '未上传' }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="审批状态">
              <template slot-scope="scope">
                {{ jobTicketStatus[scope.row.status] }}
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="220">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="exportJob(scope.row)">导出</el-button>
                <div style="display: inline-block;">
                  <el-upload
                    style="margin: 0 10px;"
                    class="upload-demo"
                    action="" 
                    :show-file-list="false"
                    :before-upload="beforeAvatarUpload"
                    :http-request="handleUpload"
                    :on-success="handleSuccess">
                    <el-button type="text" size="small" :disabled="scope.row.status===1 || scope.row.status===2" @click="importJobId=scope.row.id">上传作业篇</el-button>
                  </el-upload>
                </div>
                <el-button type="text" size="small" :disabled="scope.row.status===1 || scope.row.status===2"  @click="submit(scope.row.id, 'one')">提交审核</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <el-row v-else>
        <el-col>
          <el-table ref="multipleTable" :data="tableData" v-loading="loading">
            <el-table-column prop="jobCode" label="交底单名称">
              <template slot-scope="scope">
                {{ jobTypes[scope.row.jobCode] }}
              </template>
            </el-table-column>
            <el-table-column prop="code" label="交底单编号">
            </el-table-column>
            <el-table-column prop="status" label="审批状态">
              <template slot-scope="scope">
                {{ jobTicketStatus[scope.row.status] }}
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="200">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="officeOnline(scope.row.attachment)">详情</el-button>
                <div style="display: inline-block;" >
                  <el-popconfirm
                    style="margin-left: 10px;"
                    confirm-button-text='确定'
                    cancel-button-text='取消'
                    icon="el-icon-info"
                    icon-color="#67c23a"
                    title="是否通过该审核？"
                    @confirm="process(scope.row.id, 2)">
                    <el-button type="text" size="small" :disabled="scope.row.status!=1" slot="reference">通过</el-button>
                  </el-popconfirm>
                  <el-popconfirm
                    style="margin-left: 10px;"
                    confirm-button-text='确定'
                    cancel-button-text='取消'
                    icon="el-icon-info"
                    icon-color="red"
                    title="是否拒绝该审核？"
                    @confirm="process(scope.row.id, 3)">
                    <el-button type="text" :style="scope.row.status!=1 ? 'color: #C0C4CC;' : 'color: red;'" size="small" :disabled="scope.row.status!=1" slot="reference">拒绝</el-button>
                  </el-popconfirm>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </div>
  </div>
</template>
<script>
import { getJobDetail, submitJob, auditJob, saveAttachments, exportJobTicket } from '@/api/jobTicket/index.js'
import { getDics } from '@/api/utils/index'
export default {
  name: "detailView",
  props:{
    detailId: {
      type: Number
    },
    type: {
      type: String
    }
  },
  data() {
    return {
      elLoading: false,
      importJobId: null,
      selectJobs: [],
      workId: null,
      jobTypes: {},
      jobTicketStatus: {},
      tableData: [
        // {id: 1, jobCode: 'job001', code: 'KFC123456', attachment: '', status: 0},
        // // https://newjieyin.oss-cn-beijing.aliyuncs.com/ticket/1/101.docx
        // {id: 2, jobCode: 'job010', code: 'KFC123456', attachment: '', status: 0},
        // {id: 3, jobCode: 'job011', code: 'KFC123456', attachment: 'https://newjieyin.oss-cn-beijing.aliyuncs.com/ticket/1/101.pdf', status: 2},
      ],
      loading: false
    };
  },
  created() {
    
  },
  async mounted() {
    await this.getDicList()
    this.getDetail()
  },
  methods: {
    async getDicList() {
      getDics(['jobTypes', 'jobTicketStatus']).then(res => {
        this.jobTypes = res.data.jobTypes
        this.jobTicketStatus = res.data.jobTicketStatus
      })
    },
    getDetail() {
      if(!this.detailId) return
      this.loading = true
      getJobDetail({
        surveyId: this.detailId
      }).then(res=> {
        this.tableData = res.data
        this.loading = false
      }).catch(err=>{
        this.loading = false
      })
    },
    submit(id, type) {
      let ids = []
      if(type === 'one') {
        if(!id) return
        ids = [id]
      } else {
        ids = this.selectJobs.filter(item => item.id && item.status < 2)
        .map(item => { return item.id })
      }
      if(ids.length < 1) return
      submitJob(ids).then(res => {
        this.getDetail()
      })
    },
    process(id, status) {
      auditJob({
        bizId: id,
        toStatus: status
      }).then(res=> {
        this.getDetail()
      })
    },
    checkStatus(row) {
      let log = row.status===1 || row.status===2 ? false : true
      return log;
    },
    handleSelectionChange(val) {
      this.selectJobs = val;
    },
    officeOnline(url) {
      if(!url) {
        this.$message.warning('该交底单未上传附件，无法预览！')
        return
      }
      if(url.indexOf('.pdf') != -1) {
        window.open(url)
      } else if(url.indexOf('.docx') != -1){
        url = 'https://view.officeapps.live.com/op/view.aspx?src=' + url
        window.open(url)
      } else {
        this.$message.warning('上传附件存在异常，无法预览！')
      }
    },
    //导出交底单
    exportJob(row) {
      if(!row.id) return
      if(row.attachment && row.attachment.indexOf('http') != -1) {
        if(row.attachment.indexOf('.pdf') != -1) {
          window.open(row.attachment)
        } else {
          window.location.href = row.attachment
        }
        return
      }

      let params = {id: row.id}
      this.openLoading()
      exportJobTicket(params).then(res => {
        let blob = res
        let reader = new FileReader()
        reader.readAsDataURL(blob)
        reader.onload = (e) => {
          let a = document.createElement('a')
          a.download = row.typeName ? row.typeName + '.docx' : '交底单' + '.docx'
          a.href = e.target.result
          document.body.appendChild(a)
          a.click()
          document.body.removeChild(a)
        }
        this.closeLoading()
      }).catch(error => {
        this.closeLoading()
      })
    },
    beforeAvatarUpload(file) {
      let fileType = file.name.substring(file.name.lastIndexOf(".") + 1);
      if (fileType === 'pdf' || fileType === 'docx') {
          console.log('file');
      } else {
        this.$message.error("文件类型必须为docx或pdf格式")
        return false
      }
    },
    //图片上传
    handleUpload(option) {
      this.$ossUpload({
        path: option.file.name,
        file: option.file,
        folder: "ticket",
        done: res => {
          let fileUrl = res.res.requestUrls[0].split("?")[0];
          option.onSuccess(fileUrl)
        },
        fail: err => {
          console.log(err)
        }
      });
    },
    handleSuccess(res, file) {
      saveAttachments({
        id: this.importJobId,
        attachment: res
      }).then(res=>{
        this.$message.success("上传成功")
        this.getDetail()
      })
    },
    openLoading(){
      this.elLoading = this.$loading({
        lock: true,
        text: '加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
    },
    closeLoading(){
      this.elLoading.close();
    },
  }
};
</script>
<style scoped="scoped" lang="scss">
.detail_box {
  padding: 20px 20px 40px 20px;
}
</style>
